//
//  MainViewController.swift
//  微博
//
//  Created by xm on 2018/3/17.
//  Copyright © 2018年 xm. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 主控制器
class MainViewController: UITabBarController {

    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

         initChildControllers()//初始化所有自控制器
         setupComposeButton()//设置中间的+号按钮
         setupNotificationObser()
         setupTimer()
         checkFirstUse()
    }
    
    //中间+号按钮点击
    @objc func onComposeButtonClick() {
        
    }
    
    deinit {
        //销毁始终定时
        timer?.invalidate()
        removeNotificatonObserver()
    }
}


// MARK: - 注册通知回调方法
extension MainViewController{
    
    func setupNotificationObser() -> () {
        NotificationCenter.default.addObserver(self, selector: #selector(onGoToLogin),
                                               name: NSNotification.Name(WBGoToLoginNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onTokenError),
                                               name: NSNotification.Name(WBTokenErrorNotification), object: nil)
    }
    
    func removeNotificatonObserver() {
        NotificationCenter.default.removeObserver(self)
    }
    
    func onGoToLogin(){
        let vc = OAuthViewController()
        let nav = BaseNavigationController(rootViewController:vc)
        present(nav, animated: true, completion: nil)//模态弹出
    }
    
    func onTokenError() {
        SVProgressHUD.showInfo(withStatus: "登录信息失效！请重新登录")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2) {
            self.onGoToLogin()
        }
    }
    
}


// MARK: - 定时器
extension MainViewController{
    
    func setupTimer() {
         //定时轮询未读微博数量等
        timer=Timer.scheduledTimer(timeInterval: 60.0, target: self, selector:#selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    func updateTimer() {
        if !NetworkManager.shared.userLogined {
            return//用户没有登录
        }
        NetworkManager.shared.unreadCount { (count) in
            self.tabBar.items?[0].badgeValue=count > 0 ? "\(count)" : nil
            
            UIApplication.shared.applicationIconBadgeNumber=count
        }
    }
    
}


// MARK: -类似oc中的分类，可以用来切分代码块
extension MainViewController{
    
    /// 初始化子控制器
    func initChildControllers() -> Void {
        /**
        let array=[
             ["clsName":"HomeViewController","title":"首页","imageName":"tabbar_home",
                "visitorInfo":["imgName":"visitordiscover_feed_image_house","message":"关注一些人，回这里看看有什么惊喜关注一些人，回这里看看有什么惊喜"]
              ],
             ["clsName":"DiscoverViewController","title":"发现","imageName":"tabbar_discover",
               "visitorInfo":["imgName":"visitordiscover_image_message","message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]
              ],
             ["clsName":"MessageViewController","title":"消息","imageName":"tabbar_message_center",
                "visitorInfo":["imgName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]
              ],
             ["clsName":"ProfileViewController","title":"我","imageName":"tabbar_profile",
               "visitorInfo":["imgName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]
              ]
        ]
        //写文件到桌面上，一个plist xml文件
        //(array as NSArray).write(toFile: "/Users/admin/Desktop/demo.plist", atomically: true)
        //写文件到桌面上，一个plist json文件
        let data=try?JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        (data! as NSData).write(toFile: "/Users/admin/Desktop/demo.json", atomically: true)
        **/
        //优先从沙盒中取数据
        let docDir=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath=(docDir as NSString).appendingPathComponent("mainvc.json")
        var jsonData=NSData(contentsOfFile: jsonPath)
        if jsonData==nil {//如果沙盒中文件不存在，就加载默认的
            let path=Bundle.main.path(forResource: "mainvc.json", ofType: nil)
            jsonData=NSData(contentsOfFile: path!)
        }
        guard let array=try?JSONSerialization.jsonObject(with: (jsonData! as Data), options: []) as? [[String:AnyObject]]
            else {
              return
         }
        
        var childControllerList=[UIViewController]()
        for dict in array!{
            childControllerList.append(getController(dict: dict))
        }
        //添加一个占位VC
        childControllerList.insert(UIViewController(), at: 2)//中间撰写加号按钮，占位用的
        viewControllers=childControllerList//
        self.delegate=self;
    }
    
    //创建一个带有导航控制器
    func getController(dict:[String: AnyObject]) -> UIViewController {
       
        guard let clsName = dict["clsName"] as? String,
                  let title  = dict["title"] as? String,
                  let imageName  = dict["imageName"] as? String,
                  //利用反射取到VC class类
                  let cls = NSClassFromString(Bundle.main.namespace+"."+clsName) as? BaseViewController.Type,
            let visitorInfo=dict["visitorInfo"] as? [String:String]
              else {
                
            return UIViewController()
        }
        
        let vc=cls.init()
        vc.title=title
        vc.tabBarItem.image=UIImage(named: imageName)
        vc.tabBarItem.selectedImage=UIImage(named: imageName+"_highlighted")?.withRenderingMode(.alwaysOriginal)//设置渲染模式
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)//设置选中字体颜色
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)//设置字体大小
        vc.visitorInfo=visitorInfo;//访客视图数据信息
        let nav = BaseNavigationController(rootViewController:vc)
        return nav
    }
    
    //设置撰写按钮
    func setupComposeButton() {
        let btn:UIButton=UIButton()
        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        
        let count=CGFloat(childViewControllers.count)
        let w=tabBar.bounds.width/count - 1//减一是为了遮盖容错点
        btn.frame=tabBar.bounds.insetBy(dx: w*2, dy: 0)
        
        tabBar.addSubview(btn)
        //添加监听方法
        btn.addTarget(self, action:#selector(onComposeButtonClick), for: .touchUpInside)
    }
}

// MARK: - tabbar代理方法
extension MainViewController:UITabBarControllerDelegate{
    
    ///  将要选择的tabbarItem
    ///
    /// - Parameters:
    ///   - tabBarController:
    ///   - viewController:  目标控制器
    /// - Returns: 是否允许切换
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        //目标控制器的索引
        let index=(childViewControllers as NSArray).index(of: viewController)
        
        if selectedIndex==0 && index==selectedIndex {//当前选中的是首页，并且要跳转的也是首页
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! HomeViewController
            //是表格回滚到首页
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            //延迟一秒后加载刷新新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()//加载新数据
            })
        }
        
      //判断目标控制器是否是中间占位的 UIViewController
       return !viewController.isMember(of: UIViewController.self)//isMember是否是类实例，不包括子类
    }
}

// MARK: - 检查版本更新
extension MainViewController{
    
    func checkFirstUse() {
        let appVersion=Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""//app当前版本号
        
        let docDir=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let versonPath=(docDir! as NSString).appendingPathComponent("verson.txt")
        let oldVersion=try?String(contentsOfFile: versonPath, encoding: .utf8)
        
        if appVersion.isEqual(oldVersion) {//显示欢迎页面
            let wlview=WelcomeView.welcomeView() 
            self.view.addSubview(wlview)
        }else{//第一次使用这个版本，显示新特性
            try?appVersion.write(toFile: versonPath, atomically: true, encoding: .utf8)
            //显示新特性页面
            let newFeatureView=NewFeatureView.newFeatureView()
            self.view.addSubview(newFeatureView)
        }
    }
}
